<template>
  <el-dialog
      :model-value="visible"
      title="编辑签约信息"
      width="60%"
      @close="handleClose"
      :close-on-click-modal="false"
  >
    <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="rules"
        label-width="120px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="签约状态" prop="status">
            <el-select v-model="editForm.status" placeholder="请选择签约状态" style="width: 100%;">
              <el-option label="待支付" :value="0"></el-option>
              <el-option label="已生效" :value="1"></el-option>
              <el-option label="已过期" :value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="签约类型" prop="recordType">
            <el-select v-model="editForm.recordType" placeholder="请选择签约类型" style="width: 100%;">
              <el-option label="首次签约" value="首次签约"></el-option>
              <el-option label="非首次签约" value="非首次签约"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="签约机构" prop="orgId">
            <el-select v-model="editForm.orgId" placeholder="请选择签约机构" style="width: 100%;" @change="handleOrgChange">
              <el-option v-for="item in orgOptions" :key="item.id" :label="item.orgName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="签约团队" prop="teamId">
            <el-select v-model="editForm.teamId" placeholder="请选择签约团队" style="width: 100%;">
              <el-option v-for="item in teamOptions" :key="item.id" :label="item.teamName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="服务包" prop="pakId">
            <el-select v-model="editForm.pakId" placeholder="请选择服务包" style="width: 100%;">
              <el-option v-for="item in packageOptions" :key="item.id" :label="item.packageName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="费用 (元)" prop="fee">
            <el-input-number v-model="editForm.fee" :precision="2" :step="10" :min="0" style="width: 100%;" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="申请时间" prop="applyTime">
            <el-date-picker
                v-model="editForm.applyTime"
                type="datetime"
                placeholder="选择申请时间"
                style="width: 100%;"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="生效日期" prop="effectiveTime">
            <el-date-picker
                v-model="editForm.effectiveTime"
                type="datetime"
                placeholder="选择生效日期"
                style="width: 100%;"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleSave">保 存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ElMessage } from 'element-plus';
import { findAllSysOrganization } from "../api/SysOrganization.js";
import { queryTeamsByOrgId } from "../api/SysTeamOrganization.js";
import { queryPackagesByOrgId } from "../api/SysOrganization.js";
import { updateRecord } from "../api/record.js";

export default {
  name: 'RecordEditDialog',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    editData: {
      type: Object,
      default: () => ({}),
    },
  },
  emits: ['update:visible', 'save'],
  data() {
    return {
      editForm: {},
      orgOptions: [],
      teamOptions: [],
      packageOptions: [],
      rules: {
        status: [{ required: true, message: '请选择签约状态', trigger: 'change' }],
        recordType: [{ required: true, message: '请选择签约类型', trigger: 'change' }],
        orgId: [{ required: true, message: '请选择签约机构', trigger: 'change' }],
        teamId: [{ required: true, message: '请选择签约团队', trigger: 'change' }],
        pakId: [{ required: true, message: '请选择服务包', trigger: 'change' }],
        fee: [{ required: true, message: '请输入费用', trigger: 'blur' }],
        applyTime: [{ required: true, message: '请选择申请时间', trigger: 'change' }],
        effectiveTime: [{ required: true, message: '请选择生效日期', trigger: 'change' }],
      },
    };
  },
  watch: {
    // 监听 props.editData 的变化
    editData: {
      async handler(newData) {
        if (newData && Object.keys(newData).length > 0) {
          // 深拷贝数据到表单
          this.editForm = JSON.parse(JSON.stringify(newData));

          // **修改点**: 当编辑数据加载后，如果存在机构ID，则立即加载对应的团队和服务包
          if (this.editForm.orgId) {
            await this.loadDependentOptions(this.editForm.orgId);
          }
        } else {
          this.editForm = {};
          this.teamOptions = [];
          this.packageOptions = [];
        }

        this.$nextTick(() => {
          if (this.$refs.editFormRef) {
            this.$refs.editFormRef.clearValidate();
          }
        });
      },
      immediate: true,
      deep: true,
    }
  },
  methods: {
    handleClose() {
      this.$emit('update:visible', false);
    },
    async getOrgOptions() {
      try {
        let { data: data } = await findAllSysOrganization();
        this.orgOptions = data.data;
      } catch (error) {
        ElMessage.error('加载机构列表失败！');
        console.error(error);
      }
    },
    // 2. 新增方法：处理机构选择变化的逻辑
    async handleOrgChange(newOrgId) {
      this.editForm.teamId = null;
      this.editForm.pakId = null;

      // b. 清空团队和服务包的下拉选项
      this.teamOptions = [];
      this.packageOptions = [];

      // c. 根据新的机构ID加载对应的选项
      if (newOrgId) {
        await this.loadDependentOptions(newOrgId);
      }
    },
    // 3. 新增方法：封装加载团队和服务包的逻辑，方便复用
    async loadDependentOptions(orgId) {
      try {
        // 使用 Promise.all 并发请求，提高效率
        const [teamRes, packageRes] = await Promise.all([
          queryTeamsByOrgId(orgId),
          queryPackagesByOrgId(orgId)
        ]);
        console.log(teamRes.data);
        console.log(packageRes.data);
        this.teamOptions = teamRes.data.data;
        this.packageOptions = packageRes.data.data;
      } catch (error) {
        ElMessage.error('加载团队或服务包列表失败！');
        console.error(error);
      }
    },
    async handleSave() {
      console.log("保存签约记录：", this.editForm);
      if (!this.$refs.editFormRef) return;
      this.$refs.editFormRef.validate(async (valid) => {
        if (valid) {
          try {
            const response = await updateRecord(this.editForm);
            const data = response.data;
            if (data.code === 200) {
              this.$message.success(data.msg);
              this.$emit('save', this.editForm); // 只在成功后关闭弹窗
            } else {
              this.$message.error(data.msg);
            }
          } catch (error) {
            this.$message.error('保存失败，请重试！');
            console.error('保存签约记录失败:', error);
          }
        } else {
          ElMessage.error('表单信息有误，请检查！');
          return false;
        }
      });
    },
  },
  mounted() {
    // 仅加载机构列表，团队和服务包按需加载
    this.getOrgOptions();
  }
};
</script>

<style scoped>
/* 如果需要可以添加一些样式 */
.dialog-footer {
  text-align: right;
}
</style>